﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Ipmce.RemoteVoting.Frontend.VotingApplication.Utils;

namespace Ipmce.RemoteVoting.Frontend.VotingApplication.ViewModel
{
	class CertificateAuthorizationViewModel : ViewModelBase, ICertificateDataProvider
	{
		private readonly ICertificateProvider _certificateProvider;
		private readonly CertificateInfo[] _certificatesInfo;

		public CertificateAuthorizationViewModel(ICertificateProvider certificateProvider)
		{
			_certificateProvider = certificateProvider;
			_certificatesInfo = _certificateProvider.GetPrivateCertificateInfos();
			CertificateNames = new ReadOnlyCollection<string>(_certificatesInfo.Select(i => i.DistinguishName).ToList());
			SelectedCertificateIndex = -1;
		}

		public bool IsDataReady()
		{
			return -1 != SelectedCertificateIndex;
		}

		public X509Certificate2 Certificate
		{
			get
			{
				if (!IsDataReady())
				{
					throw new InvalidOperationException("Certificate ain't selected");
				}
				return _certificateProvider.GetCertificate(_certificatesInfo[SelectedCertificateIndex].Thumbprint);
			}
		}

		public ReadOnlyCollection<string> CertificateNames { get; private set; }

		public int SelectedCertificateIndex { get; set; }
	}
}
